/**
 * 
 */

var ctx;
var g_x = 0, g_y = 0;
var time_interval = 100;
var debug;
var g_canvasTop;
var g_canvasLeft;
var diffX, diffY;
var g_subPollAswYn="N";
var g_practiceYn="N";
var g_mainTimeIntervalId;
var g_ptStatCd;

var g_isConnected = true;
var g_avatarId = "";
var g_avatarScoreSpanObj, g_rankSpanObj, g_totalSpanObj, g_geniusSpanObj, g_stupidSpanObj;
var g_monitorObj;
var g_avatarTypeRadioTbodyObj;

$(window.document).ready(function() {
//	document.onkeydown = keyevent;

	g_avatarId = $("#avatarId").val();
	if( g_avatarId==null || g_avatarId.length==0 ) {
		alert("잘못된 접근입니다.\n다시 로그인 해주시기 바랍니다.");
		location.href="loginPage.do";
		return null;
	}

	//"점수 (순위/총원)" 출력 및 연결 끊어지면 메시지 출력을 위한 초기 설정
	g_isConnected = true;
	g_avatarScoreSpanObj = $("#avatarScoreSpan");
	g_rankSpanObj = $("#rankSpan");
	g_totalSpanObj = $("#totalSpan");
	g_geniusSpanObj = $("#geniusSpan");
	g_stupidSpanObj = $("#stupidSpan");
	
	g_monitorObj = $("#monitor");
	g_avatarTypeRadioTbodyObj = $("#avatarTypeRadioTbody");

	// smartphone event binding
	phoneEventBinding();

	// open canvas
	openCanvas();

	// draw avatar
//	drawAvatar();

	// init
	init();

	g_mainTimeIntervalId = setInterval(function() {
		flush();
	}, time_interval);

	// temp
	// $("#remoconCanvasDiv").hide();
});

function init() {
	debug = $("#debug");
	g_canvasTop = $("#remoconCanvas").css("top").replace("px", "");
	g_canvasLeft = $("#remoconCanvas").css("left").replace("px", "");
	$("#avatarType" + $("#initAvatarType").val()).attr("checked", "checked");
	setRemoconMode();
}
// javascript 이벤트를 모아 두었다가 time_interval 간격으로 서버에 전송
function flush() {
	if (g_x != 0 || g_y != 0 || g_ptStatCd=="50") {
		sendMessage(g_avatarId, g_x, g_y);
		g_x = 0;
		g_y = 0;
	}
}

// open canvas
function openCanvas() {
	alert("welcome to PPS!\nJoin presentation using your joystick!");
	var canvas = document.getElementById("remoconCanvas");
	ctx = canvas.getContext("2d");
	drawCircle(150, 150, 30, "#123456");
}

function phoneEventBinding() {
	document.getElementById("remoconCanvas").ontouchstart = showInfoTouch;
	document.getElementById("remoconCanvas").ontouchmove = showInfoTouch;
	document.getElementById("remoconCanvas").ontouchend = showInfoTouch;
	document.getElementById("remoconCanvas").ontouchcancel = showInfoTouch;
}

function drawCircle(x, y, r, color) {
	ctx.beginPath();
	ctx.fillStyle = "#FFFFFF";
	ctx.fillRect(0, 0, 300, 300);
	ctx.fillStyle = color;
	ctx.arc(x, y, r, 0, 2 * Math.PI, true);
	ctx.fill();
}

function resetCircle() {
	ctx.beginPath();
	ctx.fillStyle = "#FFFFFF";
	ctx.fillRect(0, 0, 300, 300);
	ctx.fillStyle = "#123456";
	ctx.arc(150, 150, 30, 0, 2 * Math.PI, true);
	ctx.fill();
}

var type, t, i;
function showInfoTouch(event) {
	event.preventDefault();
	type = event.type;

	for (i = 0; i < event.touches.length; i++) {
		t = event.touches[i];
		if (type == "touchmove") {
			drawCircle((t.pageX - g_canvasLeft), (t.pageY - g_canvasTop), 30,
					"#0000FF");
			diffX = (t.pageX - g_canvasLeft) - 150;
			diffY = (t.pageY - g_canvasTop) - 150;
			g_x = g_x + diffX;
			g_y = g_y + diffY;
			setTimeout("resetCircle()", 1000);
		}
	}
}

function keyevent() {
	if (event.keyCode == 37)
		moveLeft();
	if (event.keyCode == 38)
		moveUp();
	if (event.keyCode == 39)
		moveRight();
	if (event.keyCode == 40)
		moveDown();
}

function moveLeft() {
	g_monitorObj.html("Left");
	x -= 10;
}

function moveUp() {
	g_monitorObj.html("Up");
	y -= 10;
}

function moveDown() {
	g_monitorObj.html("Down");
	y += 10;
}

function moveRight() {
	g_monitorObj.html("Right");
	x += 10;
}

function submitAsw() {
	var ptId = $("#ptId").val();
	var pollId = $("#pollId").val();
	var avatarId = g_avatarId;
	var aswVal = $("#aswVal").val();
	aswVal = aswVal.replace(/\?/g, "").replace(/&/g, "");
	url = "submitAsw.json";
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		data : "ptId=" + ptId + "&pollId=" + pollId + "&avatarId=" + avatarId
				+ "&aswVal=" + aswVal,
		async : true,
		success : function(data) {
			if (data == null) {
				debug("data is null");
				return null;
			}
			if (data.successYn == 'Y') {
				//g_subPollAswYn = "Y";	//재실행 방지
				setRemoconMode();
			}
		},
		error : function(data, status, error) {
			alert("답변 전송 실패\n데이터 전송 중 문제가 발생하였습니다.\n\n[" + status + "] " + error);
		}
	});
}

// xDist 이동방향
var avatarType, url;
function sendMessage(avatarId, xDist, yDist) {
	avatarType = g_avatarTypeRadioTbodyObj.find("input:radio[name='avatarType']:checked").val();
	if (avatarType == null || avatarType == "undefined")
		avatarType = "10";
	url = "remoconAjax.json";
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		data : "avatarId=" + avatarId + "&xDist=" + xDist + "&yDist=" + yDist
				+ "&avatarType=" + avatarType,
		async : true,
		success : function(data) {
			if (data == null) {
				debug("data is null");
				return null;
			}
			if (data.ptInfVO != null) {
				g_ptStatCd = data.ptInfVO.ptStatCd;
				switch (data.ptInfVO.ptStatCd) {
				case "10":
					setRemoconMode();
					break;// 준비중
				case "20":
					setWatingMode();
					break;// 진행중
				case "30":
					setPollMode(data);
					break;// 설문진행중
				case "40":
					g_subPollAswYn = "N";//재실행 방지
					setRemoconMode();
					break;// 설문종료
				case "50":
					setPractice(data);	//재실행 방지
					break; // 실습진행
				case "99":
					break;// 종료
				default:
					setRemoconMode();
				}
			}

			var rank = data.rank;
			if( rank==-1 && g_isConnected ) {
				g_isConnected = false;
				alert("연결이 끊어졌습니다.\n\n계속 이용하시려면 다시 로그인 해주시기 바랍니다.\n\n이용에 불편을 드려 죄송합니다.");
				location.href="loginPage.do";
				return null;
			}
			var avatarScore = data.avatarVO.avatarScore;
			var total = data.total;
			g_avatarScoreSpanObj.text(avatarScore);
			g_rankSpanObj.text(rank);
			g_totalSpanObj.text(total);
			if( rank==1 && avatarScore>0 ) {
				g_stupidSpanObj.hide();
				g_geniusSpanObj.show();
			}
			else if( rank>=total && avatarScore>0 ) {
				g_geniusSpanObj.hide();
				g_stupidSpanObj.show();
			}
			else {
				g_geniusSpanObj.hide();
				g_stupidSpanObj.hide();
			}
		},
		error : function(data, status, error) {
			alert("데이터 전송 중 문제가 발생하였습니다.\n\n[" + status + "] " + error);
		}
	});
}

function setWatingMode() {
	hideAll();
	$("#remoconCanvas").show();
}

function setRemoconMode() {
	hideAll();
	$("#remoconCanvas").show();
	$("#pollId").val('');
}

function setPollMode(data){
	if(data.pollInfVO!=null){
		if(data.pollInfVO.qstTypeCd=="SUB"){
			if(g_subPollAswYn=="N"){
				$("#subPollDiv").show();
				$("#remoconCanvas").hide();
				$("#qstVal").text(data.pollInfVO.qstVal);
				$("#pollId").val(data.ptInfVO.pstPollId);
			}
		}else if(data.pollInfVO.qstTypeCd=="OBJ"){
			g_subPollAswYn = "N";
			$("#subPollDiv").hide();
			$("#remoconCanvas").show();
		}
	}
}

function buttonEventBinding() {
	$("#btnUpLeft").click(function() {
		moveLeft();
		moveUp();
	});
	$("#btnUp").click(function() {
		moveUp();
	});
	$("#btnUpRight").click(function() {
		moveRight();
		moveUp();
	});
	$("#btnLeft").click(function() {
		moveLeft();
	});
	$("#btnRight").click(function() {
		moveRight();
	});

	$("#btnDownLeft").click(function() {
		moveDown();
		moveLeft();
	});

	$("#btnDown").click(function() {
		moveDown();
	});

	$("#btnDownRight").click(function() {
		moveDown();
		moveRight();
	});
}

// practice message 받았다면
function setPractice(data){
	hideAll();
	if(data.ptInfVO){
		var message = data.ptInfVO.message;
		if(message!=null && message != ""){
			$("#practiceDiv").show();
			$("#practiceActionMessage").html(message);
		}
	}
}

/*
var g_practiceInterval = null;
var g_practiceActionList;
var g_practiceListIndex;
function setPractice(data) {
	hideAll();
	$("#practiceDiv").show();
	clearInterval(g_mainTimeIntervalId);
	g_practiceInterval = null;
	g_practiceListIndex = 0;
	g_practiceActionList = data.practiceDataList;
	showPracticeView();
}

function showPracticeView() {
	
	if (g_practiceInterval != null) {
		clearInterval(g_practiceInterval);
	}
	
	if(g_practiceListIndex==g_practiceActionList.length-1){
		$("#closePracticeBtn").show();
	}
	
	var message = g_practiceActionList[g_practiceListIndex].message;
	var sustainmentTime = g_practiceActionList[g_practiceListIndex].sustainmentTime;
	$("#practiceActionMessage").text(message);
	g_practiceListIndex++;
	
	if (g_practiceListIndex < g_practiceActionList.length) {
		g_practiceInterval = setInterval(showPracticeView, sustainmentTime * 1000);
	}
}
*/

function hideAll() {
	$("#subPollDiv").hide();
	$("#remoconCanvas").hide();
	$("#practiceDiv").hide();
	$("#closePracticeBtn").hide();
}

function closePractice() {
	g_practiceYn = "Y";
	g_mainTimeIntervalId = setInterval(function() {
		flush();
	}, time_interval);
	setRemoconMode();
	
}

// 아바타 모양 변경
//function drawAvatar() {
//	avatarType = $("#avatarType").val();
//	$("#avatarTypeImg").attr("src", getImgSrc(avatarType));
//}